import Watcher from "./Watcher";

export default class Compiler{
  constructor(el,vue) {
    this.$vue = vue;
    this.$el = document.querySelector(el)
    if (this.$el){
      // 调用函数，节点变为fragment
      let $fragment = this.node2Fragment(this.$el)
      this.compile($fragment)
      this.$el.appendChild($fragment)
    }
  }
  node2Fragment(el){
    var fragment = document.createDocumentFragment()
    var child
    while (child = el.firstChild){
      fragment.appendChild(child)
    }
    return fragment
  }
  compile(el){
    var childNodes = el.childNodes
    var self = this
    var reg = /\{\{(.*)\}\}/;
    childNodes.forEach(node=>{
      let text = node.textContent || ''
      if (node.nodeType == 1){
        self.compileElement(node);
      } else if (node.nodeType == 3 && reg.test(text)) {
        let keys = text.match(reg)[1]
        console.log(keys);
        self.compileText(node,keys)
      }
    })
  }
  compileElement(node){
    var nodeAttrs = node.attributes;
    var self = this;
    [...nodeAttrs].forEach(attr =>{
      var attrName = attr.name;
      var value = attr.value;
      var dir = attrName.substring(2)
      // 判断是不是指令
      if (attrName.indexOf('v-') == 0) {
        // v- 开头的是指令
        if (dir == 'model') {
          new Watcher(self.$vue,value,value=>{
            node.value = value
          })
          var v = self.getVueval(self.$vue,value)
          node.value = v
          node.addEventListener('input', e=>{
            var newValue = e.target.value;
            self.setVueval(self.$vue,value,newValue)
            v = newValue
          })
        } else if (dir == 'if') {
          console.log('if指令' + value)
        }
      }
    })
  }
  compileText(node,name){
    node.textContent = this.getVueval(this.$vue,name)
    new Watcher(this.$vue,name,value=>{
      node.textContent = value;
    })
  }
  getVueval(vue,exp){
    var val = vue;
    exp = exp.split('.')
    exp.forEach(k=>{
      val = val[k]
    })
    return val
  }
  setVueval(vue,exp,value){
    var val = vue;
    exp = exp.split('.')
    exp.forEach((k,i)=>{
      if (i <exp.length - 1){
        val = val[k]
      } else {
        val[k] = value
      }
    })
    return val
  }
}